﻿using Core.Domain;
using Core.DomainServices;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Infrastructure.DomainServices
{
    public class ExportToWordV2 : IDocumentService
    {
        public readonly IDataRepository dataRepository;
        private readonly IAppConfig appConfig;
        public InvoiceInfo Invoice { get; set; }
        public List<ProductItem> ProductItems { get; set; }
        public Dictionary<string, string> CompanyInformation { get; set; }

        public ExportToWordV2(IDataRepository dataRepository, IAppConfig appConfig)
        {
            this.dataRepository = dataRepository;
            this.appConfig = appConfig;
        }

        public IList<string> Export(string outputFolder)
        {
            string path = Directory.GetCurrentDirectory().Replace("bin" + Path.DirectorySeparatorChar + "Debug", "DataSample") + Path.DirectorySeparatorChar + "TemplateData.xlsx";
            var ds = dataRepository.ReadData(path);
            var invoices = new List<InvoiceInfo>();
            var productItems = new List<ProductItem>();
            var results = new List<string>();
            if (ds != null && ds.Tables.Count > 0)
            {
                if (ds.Tables.Contains(Constants.Invoice.TABLE))
                {
                    System.Data.DataTable table = ds.Tables[Constants.Invoice.TABLE];
                    foreach (DataRow row in table.Rows)
                    {
                        int invoiceNo = new Random().Next(1000, 4000);
                        var invoice = new InvoiceInfo(row);
                        invoice.InvoiceNo = invoiceNo.ToString();
                        invoices.Add(invoice);
                    }
                }

                if (ds.Tables.Contains(Constants.ProductItem.TABLE))
                {
                    System.Data.DataTable table = ds.Tables[Constants.ProductItem.TABLE];
                    foreach (DataRow row in table.Rows)
                    {
                        productItems.Add(new ProductItem(row));
                    }
                }

                if (invoices.Any())
                {
                    var company = appConfig.GetXMLValues();
                    string templateDoc = Directory.GetCurrentDirectory().Replace("bin" + Path.DirectorySeparatorChar + "Debug", "Templates") + Path.DirectorySeparatorChar + "WordTemplateInvoice.docx";
                    foreach (var item in invoices)
                    {
                        if (invoices.IndexOf(item) > 0)
                        {
                            var items = productItems.Where(d => d.OrderGUID == item.OrderGUID).ToList();
                            Invoice = item;
                            ProductItems = items;
                            CompanyInformation = company;

                            // Copy a new file name from template file
                            string destinationFile = outputFolder + Path.DirectorySeparatorChar + Invoice.OrderGUID + ".docx";
                            File.Copy(templateDoc, destinationFile, true);

                            using (var mydoc = WordprocessingDocument.Open(destinationFile, true))
                            {

                                //After openning your document, you can change type of your document after adding additional parts into your document.
                                mydoc.ChangeDocumentType(WordprocessingDocumentType.Document);


                                var mainPart = mydoc.MainDocumentPart;
                                var document = mainPart.Document;
                                var body = document.Body;
                                body.InnerXml = ReplacePlaceHoldersInTemplate(body.InnerXml);

                                document.Save();
                                results.Add(destinationFile);
                            }
                            
                        }
                    }
                }
            }
            return results;
        }

        private string ReplacePlaceHoldersInTemplate(string templateBody)
        {
            templateBody = templateBody.Replace("#CompanyName#", CompanyInformation["CompanyName"]);
            templateBody = templateBody.Replace("#StreetAddress#", CompanyInformation["StreetAddress"]);
            templateBody = templateBody.Replace("#ZipCode#", CompanyInformation["ZipCode"]);
            templateBody = templateBody.Replace("#PhoneNumber#", CompanyInformation["PhoneNumber"]);
            return templateBody;
        }
    }
}
